/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import Datatypes.DataJuego;
import Datatypes.DataPerfil;
import Datatypes.DataVersion;
import Interfaces.*;
import Fabricas.Factory;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author dalep0
 */
public class JIFVersionado extends javax.swing.JInternalFrame {

    private Factory f = null;
    private IJuego ij = null;
    private IVersion iv = null;
    private List<DataVersion> listadv = null;
    
    public JIFVersionado(Factory f) throws Exception{
        
        this.f = f;
        this.ij = f.getIJuego();
        this.iv = f.getIVersion();
               
        initComponents();
        cargarPendientes();
        BloquearComponentes();
        
        
    }
    
    private void cargarPendientes(){
        try {
            
            DefaultTableModel tm = (DefaultTableModel) this.jTable1.getModel();
            listadv = this.iv.listarPendientes();
            int rows = 0;

            for (DataVersion dv : listadv) {
                
                tm.addRow(new Object[rows]);
                tm.setValueAt(dv.getNombreJuego(), rows, 0);
                tm.setValueAt(dv.getVersion(), rows, 1);
                tm.setValueAt(dv.getNombreDesarrollador(), rows, 2);
                rows++;
            }
            
            
        }
        
        catch (Exception e) {
            
            JOptionPane.showMessageDialog(this, e.getMessage(), "Error!", JOptionPane.ERROR_MESSAGE, null);
            
        }
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jButtonAceptar = new javax.swing.JButton();
        jButtonCancelar = new javax.swing.JButton();
        jToggleButtonAprobar = new javax.swing.JToggleButton();
        jToggleButtonRechazar = new javax.swing.JToggleButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jLabel2 = new javax.swing.JLabel();

        setClosable(true);

        jTable1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null}
            },
            new String [] {
                "Juego", "Version", "Desarrollador"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jLabel1.setFont(new java.awt.Font("Ubuntu", 1, 15)); // NOI18N
        jLabel1.setText("Versiones Pendientes");

        jButtonAceptar.setText("Aceptar");
        jButtonAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAceptarActionPerformed(evt);
            }
        });

        jButtonCancelar.setText("Cancelar");
        jButtonCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCancelarActionPerformed(evt);
            }
        });

        jToggleButtonAprobar.setText("Aprobar");
        jToggleButtonAprobar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jToggleButtonAprobarActionPerformed(evt);
            }
        });

        jToggleButtonRechazar.setText("Rechazar");
        jToggleButtonRechazar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jToggleButtonRechazarActionPerformed(evt);
            }
        });

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jTextArea1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextArea1KeyReleased(evt);
            }
        });
        jScrollPane2.setViewportView(jTextArea1);

        jLabel2.setFont(new java.awt.Font("Ubuntu", 1, 15)); // NOI18N
        jLabel2.setText("Motivo rechazo:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jToggleButtonAprobar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jToggleButtonRechazar, javax.swing.GroupLayout.DEFAULT_SIZE, 99, Short.MAX_VALUE))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel2)
                                        .addGap(0, 0, Short.MAX_VALUE))
                                    .addComponent(jScrollPane2)))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 518, Short.MAX_VALUE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jButtonCancelar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButtonAceptar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(16, 16, 16)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButtonAceptar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonCancelar))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 189, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(42, 42, 42)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jToggleButtonAprobar, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jToggleButtonRechazar)))
                .addContainerGap(44, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelarActionPerformed
        this.dispose();
        JIFInicial.BloquearJFInicial();
    }//GEN-LAST:event_jButtonCancelarActionPerformed

    private void jToggleButtonRechazarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButtonRechazarActionPerformed
        if(this.jToggleButtonRechazar.isSelected() ){
        
            this.jToggleButtonAprobar.setSelected(false);            
            this.jTextArea1.setEnabled(true);
            if(this.jTextArea1.getText().length() == 0){
                
                this.jButtonAceptar.setEnabled(false);
                
            }
            
                    
        }   
        else{
            
            this.jButtonAceptar.setEnabled(false);
            this.jTextArea1.setEnabled(false);
            this.jTextArea1.setText("");
            
        }
    
    }//GEN-LAST:event_jToggleButtonRechazarActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
       int row = jTable1.rowAtPoint(evt.getPoint());
       int col = jTable1.columnAtPoint(evt.getPoint());
       if (row >= 0 && col >= 0) {
           
           Integer indice = this.jTable1.getSelectedRow();
           if(this.jTable1.getValueAt(indice, 0) != null) {
           
               DesbloquearComponentes();
           
           }
           else{
               
               BloquearComponentes();
               this.jToggleButtonAprobar.setSelected(false);
               this.jToggleButtonRechazar.setSelected(false);
               
           }
           
            
        }
    }//GEN-LAST:event_jTable1MouseClicked

    private void jToggleButtonAprobarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButtonAprobarActionPerformed
        if(this.jToggleButtonAprobar.isSelected()){
            
            this.jToggleButtonRechazar.setSelected(false);            
            this.jTextArea1.setText("");
            this.jTextArea1.setEnabled(false);
            this.jButtonAceptar.setEnabled(true);
            
            
        }
        else{
            
            this.jButtonAceptar.setEnabled(false);
            
        }
                
    }//GEN-LAST:event_jToggleButtonAprobarActionPerformed

    private void jTextArea1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextArea1KeyReleased
        if(this.jTextArea1.getText() == null){
            
            this.jButtonAceptar.setEnabled(false);
            
        }
        else{
            
            this.jButtonAceptar.setEnabled(true);
            
        }
    }//GEN-LAST:event_jTextArea1KeyReleased
    
    private DataVersion selectedDataVersion(String juego, List<DataVersion> lista){
        DataVersion dv = null;
        Boolean sal = false;
        Iterator<DataVersion> it = this.listadv.iterator();
        while(it.hasNext() && !sal){
            
            dv = it.next();
            if(dv.getNombreJuego().equals(juego) ){
                
                sal = true;
                
            }
            
        }
        return dv;
        
    }
    
    private void jButtonAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAceptarActionPerformed
        try {
            Integer indice = this.jTable1.getSelectedRow();
            String juego = this.jTable1.getValueAt(indice, 0).toString();
            DataJuego dj = ij.elegirJuego(juego);
            
            if(this.jToggleButtonAprobar.isSelected()){
                          
               DataVersion dv = this.selectedDataVersion(juego, listadv);
                try{
                    
                    this.iv.altaAprobada(dv);
                    this.iv.notificarClientes(dv.getCodigoJuego(), dv.getVersion());
                    final String nomJuego = juego;
                    final int codigo = dj.getCodigo();
                    Thread t = new Thread(){
                            
                        public void run()
                        {
                            try{
                                
                                enviarMail(nomJuego,codigo);
                            
                            }
                            
                            catch (Exception e) {

                                JOptionPane.showMessageDialog(null, "Hubo un error al aprobar la version: "+e.getMessage(), "Error!", JOptionPane.ERROR_MESSAGE);
                                
                            }
                            
                        }                        
                    };
                    t.start();
                    
                    
                }
                catch (Exception e) {
                
                    JOptionPane.showMessageDialog(this, "Hubo un error al aprobar la version: "+e.getMessage(), "Error!", JOptionPane.ERROR_MESSAGE);
                    this.dispose();
                }
                
                
            }
            else if(this.jToggleButtonRechazar.isSelected()){
                                        
               
               DataVersion dv = this.selectedDataVersion(juego, listadv);
                try {
                    
                    this.iv.altaRechazada(dv, this.jTextArea1.getText());
                    
                }
                catch (Exception e) {
                
                    JOptionPane.showMessageDialog(this, "Hubo un error al rechazar la version", "Error!", JOptionPane.ERROR_MESSAGE);
                    this.dispose();
                }
                
            }
            
            this.listadv.clear();
            JOptionPane.showMessageDialog(this, "Operación con éxito!", "Éxito", JOptionPane.INFORMATION_MESSAGE);
            JIFInicial.BloquearJFInicial();
            this.dispose();
            
        } catch (Exception e) {
            
            JOptionPane.showMessageDialog(this, e.getMessage(), "error", JOptionPane.ERROR_MESSAGE);
        
        }
        
       
        
        
    }//GEN-LAST:event_jButtonAceptarActionPerformed
    private void BloquearComponentes(){
        
        this.jButtonAceptar.setEnabled(false);
        this.jToggleButtonAprobar.setEnabled(false);
        this.jToggleButtonRechazar.setEnabled(false);
        this.jTextArea1.setEnabled(false);
        
    }
    private void DesbloquearComponentes(){
        
        this.jToggleButtonAprobar.setEnabled(true);
        this.jToggleButtonRechazar.setEnabled(true);
        
        
    }
    
    public void enviarMail(String juegostr, Integer codigo_juego)throws Exception{
        


            List<DataPerfil> lista_clientes = ij.getClientesCompranJuego(codigo_juego);
            if(lista_clientes.size()>0){
                try{
                    
                    String host = "smtp.gmail.com";
                    String to = null;
                    String subject = juegostr+" tiene nueva version!";
                    String from = "tplaymarketcomercial@gmail.com";
                    Properties props = System.getProperties();
                    props.put("mail.smtp.host", "smtp.gmail.com");
                    props.put("mail.transport.protocol", "smtp");
                    props.put("mail.smtps.auth", "true");
                    props.setProperty("mail.smtp.timeout", "10000");
                    Session mailSession = Session.getInstance(props);
                    Transport t = mailSession.getTransport("smtps");
                    t.connect(host, from,"tecnoinf");
                    //mailSession.setDebug(sessionDebug);
                    for(DataPerfil cliente : lista_clientes){

                        to = cliente.getCorreo();
                        String mensaje = cliente.getNick()+", "+"se ha subido una nueva version del juego "+juegostr+","
                                + " recuerda visitar la pagina para poder descargarla."
                                + " \nTe saluda atentamente,\nEquipo de TPlayMarket";

                        MimeMessage msg = new MimeMessage(mailSession);
                        msg.setFrom(new InternetAddress(from));
                        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
                        msg.setSubject(subject);
                        msg.setSentDate(new Date());
                        msg.setText(mensaje);

                        t.sendMessage(msg, msg.getAllRecipients());
                    }

                }
                catch(Exception e){

                    JOptionPane.showMessageDialog(this, e.getMessage(), "Error!", JOptionPane.ERROR_MESSAGE, null);

                }


            }
                
            
        
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonAceptar;
    private javax.swing.JButton jButtonCancelar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JToggleButton jToggleButtonAprobar;
    private javax.swing.JToggleButton jToggleButtonRechazar;
    // End of variables declaration//GEN-END:variables
}
